/**
 * Created with JetBrains WebStorm.
 * User: Fred_974
 * Date: 14/06/13
 * Time: 11:16
 * To change this template use File | Settings | File Templates.
 */
var connector = require('./connector');
var connection = connector.connection();
// We need our model
var Maturity = require("./Maturity");


var persistMaturitySettings = function(maturity, callback){

    var post  = {name: maturity.name, min: maturity.min, max: maturity.max }



    if(maturity.id == null){

        connection.query('INSERT INTO maturity SET ?', post, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(maturity); // Callback basicaly it's the end of the controleur
        });
    }else{
        connection.query('update maturity SET ? where id = ?',[post,maturity.id], function(err, rows, fields){



            if (err) throw err; // if there is an error we throw it
            callback(maturity); // Callback basicaly it's the end of the controleur
        });

    }


};

var findById = function(id,callback){

    connection.query('select * from maturity where id= ?', [id], function(err, rows, fields){

        if (err) throw err; // if there is an error we throw it


        // if rows length == 0 return null;
        var maturity = new Maturity();
        maturity.init(rows[0]);
        callback(maturity); // Callback basicaly it's the end of the controleur
    });

};

var findAllMaturity = function(callback){

    connection.query('select * from maturity', function(err, rows, fields){

        if (err) throw err; // if there is an error we throw it

        callback(rows); // Callback basicaly it's the end of the controleur

    });

};

var deleteMaturity = function(maturity, callback){



    if(maturity.id == null){

        connection.query('delete from maturity where id ='+maturity.id, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it
            callback(maturity); // Callback basicaly it's the end of the controleur
        });
    }else{
        connection.query('delete from maturity where id ='+maturity.id, function(err, rows, fields){



            if (err) throw err; // if there is an error we throw it
            callback(maturity); // Callback basicaly it's the end of the controleur
        });

    }
}

exports.persistMaturitySettings = persistMaturitySettings;
exports.deleteMaturity = deleteMaturity;
exports.findAllMaturity = findAllMaturity;
exports.findById = findById;

